﻿using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace Microsoft.AspNet.Identity
{

    public static class UserManagerExtensions
    {

        public static async Task<TUser> FindByPhoneNumberAsync<TUser>(this UserManager<TUser> self, string phoneNumber) where TUser : IdentityUser
        {
            return await Task.FromResult(self.Users.FirstOrDefault(x => string.Equals(x.PhoneNumber, phoneNumber)));
        }

        public static async Task<TRoleWeight> GetRoleValueAsync<TUser, TRoles, TRoleWeight>(this UserManager<TUser> self, TUser user) where TUser : IdentityUser where TRoles : struct
        {
            var roles = typeof(TRoles).ToEnumDictionary<TRoleWeight, TRoleWeight>(item => item.Value, true);
            foreach (var role in roles)
            {
                Debug.WriteLine($"Checking if user {user.Id} is in role {role.Key} : {role.Value}...");
                if (await self.IsInRoleAsync(user, role.Key))
                {
                    return await Task.FromResult(role.Value);
                }
            }
            throw new KeyNotFoundException($"The given user {user.Id} is not in any role your role holder given.");
        }

    }

}